package com.milotnt.controller;

import com.milotnt.form.MemberQueryForm;
import com.milotnt.pojo.ClassOrderEntity;
import com.milotnt.pojo.ClassTableEntity;
import com.milotnt.pojo.MemberEntity;
import com.milotnt.service.ClassOrderService;
import com.milotnt.service.ClassTableService;
import com.milotnt.service.MemberService;
import com.milotnt.vo.ClassOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ClassTableService classTableService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ClassOrderService classOrderService;

    //跳转用户主页
    @RequestMapping("/toUserMain")
    public String toUserMain(Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        model.addAttribute("member", member);
        return "userMain";
    }

    //跳转个人信息页面
    @RequestMapping("/toUserInfo")
    public String toUserInformation(Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        model.addAttribute("member", member);
        return "userInformation";
    }

    //跳转修改个人信息页面
    @RequestMapping("/toUpdateInfo")
    public String toUpdateUserInformation(HttpSession session, Model model) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        model.addAttribute("member", member);
        return "updateUserInformation";
    }

    //修改个人信息
    @RequestMapping("/updateInfo")
    public String updateUserInformation(HttpSession session, MemberEntity member, Model model) {
        try {
            MemberEntity member1 = (MemberEntity) session.getAttribute("user");
            if (member1 == null) {
                return "redirect:/userLogin";
            }

            member.setMemberAccount(member1.getMemberAccount());
            member.setCardClass(member1.getCardClass());
            member.setCardTime(member1.getCardTime());
            member.setUpdateTime(member1.getUpdateTime());
            member.setId(member1.getId());
            member.setCardNextClass(member1.getCardNextClass());

            if (!memberService.updateMemberByMemberAccount(member,model)){
                log.error("修改个人信息失败");
                return "updateUserInformation";
            }

            //重新查询更新过后的会员信息
            MemberEntity updateMember = memberService.getById(member.getId());

            // 将更新后的会员信息放入 session 和 model 中
            session.setAttribute("user", updateMember);
            model.addAttribute("member", updateMember);

            return "userInformation";
        } catch (Exception e) {
            log.error("修改个人信息异常", e);
            model.addAttribute("errorMsg", "修改个人信息异常");
            throw new RuntimeException(e);
        }
    }

    //跳转我的课程页面
    @RequestMapping("/toUserClass")
    public String toUserClass(MemberQueryForm form, Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        model.addAttribute("member", member);
        form.setMemberAccount(member.getMemberAccount());
        form.setMemberName(member.getMemberName());
        List<ClassOrderVo> classOrderList = classOrderService.selectClassOrderByMember(form);
        model.addAttribute("classOrderList", classOrderList);
        return "userClass";
    }

    //退课
    @RequestMapping("delUserClass")
    public String deleteUserClass(Long classOrderId, HttpSession session) {
        classOrderService.deleteByClassOrderId(classOrderId);
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        // 更新 session
        session.setAttribute("user", memberService.getById(member.getId()));
        return "redirect:toUserClass";
    }

    //跳转报名选课页面
    @RequestMapping("/toApplyClass")
    public String toUserApplyClass(Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        List<ClassTableEntity> classList = classTableService.findAll();
        model.addAttribute("member", member);
        model.addAttribute("classList", classList);
        return "userApplyClass";
    }

    //报名选课
    @RequestMapping("/applyClass")
    public String userApplyClass(Long classId, Model model, HttpSession session) {
        ClassTableEntity classTable = classTableService.selectByClassId(classId);
        MemberEntity member = (MemberEntity) session.getAttribute("user");

        if (member == null) {
            return "redirect:/userLogin";
        }

        if (member.getCardNextClass() <= 0){
            throw new RuntimeException("会员卡余额不足");
        }

        ClassOrderEntity classOrder = new ClassOrderEntity();

        classOrder.setClassId(classTable.getId());
        classOrder.setClassName(classTable.getClassName());
        classOrder.setCoach(classTable.getCoach());
        classOrder.setClassBegin(classTable.getClassBegin());
        classOrder.setMemberName(member.getMemberName());
        classOrder.setMemberAccount(member.getMemberAccount());

        ClassOrderEntity classOrder1 = classOrderService.selectMemberByClassIdAndMemberAccount(classOrder);

        if (classOrder1 != null) {
            model.addAttribute("alreadyEnrolled", true);

            List<ClassTableEntity> classList = classTableService.findAll();
            model.addAttribute("classList", classList); // 传递数据到页面

            return "userApplyClass"; // 返回原页面
        }

        classOrderService.insertClassOrder(classOrder);
        // 更新 session
        session.setAttribute("user", memberService.getById(member.getId()));

        return "redirect:toUserClass";
    }

    //跳转充值页面
    @RequestMapping("/toRecharge")
    public String toRecharge(Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        model.addAttribute("member", member);
        return "recharge";
    }

    //充值
    @RequestMapping("/recharge")
    public String recharge(Long rechargeAmount, Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        if (rechargeAmount == null || rechargeAmount <= 0) {
            model.addAttribute("error", "充值课时必须大于0");
            return "recharge";
        }

        // 更新会员信息
        member.setCardClass(member.getCardClass() + rechargeAmount);
        member.setCardNextClass(member.getCardNextClass() + rechargeAmount);

        boolean success = memberService.updateMemberByMemberAccount(member, model);
        if (success) {
            // 更新 session 中的用户信息
            session.setAttribute("user", memberService.getById(member.getId()));
            model.addAttribute("success", "充值成功！");
            return "redirect:/user/toRecharge?success=" + rechargeAmount;
        } else {
            model.addAttribute("error", "充值失败，请重试");
            return "recharge";
        }
    }

}
